﻿using System.Web;
using EPiServer.Common;
using EPiServer.Common.Comments;
using Joel.Net;
using JoelAbrahamsson.Web.ExtensionMethods;

namespace JoelAbrahamsson.Web.Common
{
    public class AkismetCommentValidator : ICommentValidator
    {
        private string _apiKey;
        private string _blog;

        public AkismetCommentValidator(string apiKey, string blog)
        {
            _apiKey = apiKey;
            _blog = blog;
        }

        public bool Validate(HttpContextBase httpContext, Comment comment, IAuthor author, System.Web.Mvc.ModelStateDictionary modelState)
        {
            Akismet akismet = new Akismet(_apiKey, _blog, string.Empty);

            akismet.VerifyKey();

            AkismetComment akismetComment = new AkismetComment();
            akismetComment.CommentContent = comment.Content;
            akismetComment.UserIp = comment.GetAuthorIP();
            akismetComment.CommentAuthor = author.Name;
            akismetComment.CommentAuthorEmail = author.Email;
            if(comment.Author.HasUrl())
                akismetComment.CommentAuthorUrl = author.GetUrl();
            akismetComment.UserAgent = httpContext.Request.UserAgent;
            akismetComment.Referrer = httpContext.Request.UrlReferrer.ToString();
            akismetComment.CommentType = "comment";
            akismetComment.Blog = _blog;



            bool valid = !akismet.CommentCheck(akismetComment);

            if (!valid)
                modelState.AddModelError("Comment", "Validation of your comment with Akismet (spam protection) failed.");

            return valid;
        }
    }
}
